package org.apache.ocean.main.util;

import java.io.IOException;
import java.io.InputStream;

import org.apache.lucene.store.IndexInput;

public class IndexInputStream extends InputStream {
	private IndexInput indexInput;
	private int size;

	public IndexInputStream(IndexInput indexInput) {
		this.indexInput = indexInput;
		this.size = (int)indexInput.length();
	}

	public int read(byte[] b, int offset, int len) throws IOException {
		long filePointer = indexInput.getFilePointer();
		if (len + filePointer > size) {
			int n = size - (int)filePointer;
			byte[] bytes = new byte[n];
			indexInput.readBytes(bytes, offset, bytes.length);
			System.arraycopy(bytes, 0, b, 0, bytes.length);
			return n;
		}
		indexInput.readBytes(b, offset, len);
		return len;
	}

	public int read(byte[] b) throws IOException {
		return read(b, 0, b.length);
	}

	public int read() throws IOException {
		return indexInput.readByte();
	}

	public void close() throws IOException {
		indexInput.close();
	}
}
